package cn.chitanda.weather.data.db

import cn.chitanda.weather.data.network.NetWorkService
import cn.chitanda.weather.data.weather.Basic
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

class PlaceRepository private constructor(
    private val placeDao: PlaceDao,
    private val network: NetWorkService
) {
    suspend fun addCity(city: Basic) = withContext(Dispatchers.IO) {
        placeDao.insertCity(city)
    }

    suspend fun searchCity(string: String) = withContext(Dispatchers.Default) {
        val list = network.searchCity(string).cityList!![0].basic
        list
    }

    fun getAllCity() = placeDao.getCityList()


    suspend fun deleteCity(city: Basic) {
        placeDao.deleteCity(city)
    }

    companion object {
        private var instance: PlaceRepository? = null
        fun getInstance(placeDao: PlaceDao, network: NetWorkService) =
            instance ?: synchronized(this) {
                instance ?: PlaceRepository(placeDao, network).also { instance = it }
            }
    }
}